package com.example.test.common;

import org.springframework.util.Assert;

/**
 * 统一请求返回
 */
public class BaseResponse<T> {

  public static Integer CODE_SUCCESS = 0;

  /**
   * 成功标识
   */
  protected static final Boolean FLAG_SUCCESS = true;
  /**
   * 错误标识
   */
  protected static final Boolean FLAG_ERROR = false;

  /**
   * true-成功
   * false-失败
   */
  private boolean flag;

  /**
   * 错误码，方便定位错误： 0-正常，其它都为异常
   */
  private Integer code;

  /**
   * 返回数据
   */
  private T data;

  /**
   * 错误信息
   */
  private String msg;

  public static <T> com.example.test.common.BaseResponse error(ServiceExceptionEnum serviceExceptionEnum) {
    return error(serviceExceptionEnum.getCode(),serviceExceptionEnum.getMsg());
  }

  public static <T> com.example.test.common.BaseResponse error(Integer code, String msg) {
    Assert.isTrue(!CODE_SUCCESS.equals(code), "code 必须是错误的！");
    com.example.test.common.BaseResponse<T> result = new com.example.test.common.BaseResponse<>();
    result.code = code;
    result.flag = FLAG_ERROR;
    result.msg = msg;
    return result;
  }

  public static <T> com.example.test.common.BaseResponse<T> success(T data) {
    com.example.test.common.BaseResponse<T> result = new com.example.test.common.BaseResponse<>();
    result.code = CODE_SUCCESS;
    result.flag = FLAG_SUCCESS;
    result.data = data;
    result.msg = "";
    return result;
  }

  public boolean isFlag() {
    return flag;
  }

  public void setFlag(boolean flag) {
    this.flag = flag;
  }

  public Integer getCode() {
    return code;
  }

  public void setCode(Integer code) {
    this.code = code;
  }

  public Object getData() {
    return data;
  }

  public void setData(T data) {
    this.data = data;
  }

  public String getMsg() {
    return msg;
  }

  public void setMsg(String msg) {
    this.msg = msg;
  }

  @Override
  public String toString() {
    return "BaseResponse{" +
        "code=" + code +
        ", msg='" + msg + '\'' +
        ", data=" + data +
        '}';
  }


}
